/*
     Copyright 2007 Joseph M. Ferner

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

using System;
using System.Text;

namespace OpenServers.Net.Common.Utils {
    ///<summary>
    /// Collection of utilites for working with arrays.
    ///</summary>
    public class ArrayUtils {
        ///<summary>
        /// Joins an array of objects with ", ". Calling ToString() on each object in the array.
        ///</summary>
        ///<param name="array">The array to join.</param>
        ///<returns>The joined array of items</returns>
        public static string Join<T>(T[] array) {
            return Join(", ", array);
        }

        ///<summary>
        /// Joins an array of objects with ", ". Calling ToString() on each object in the array.
        ///</summary>
        ///<param name="seperator">The string to seperate each item with.</param>
        ///<param name="array">The array to join.</param>
        ///<returns>The joined array of items</returns>
        public static string Join<T>(string seperator, T[] array) {
            if (array == null) {
                return "null";
            }
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < array.Length; i++) {
                if (i != 0) {
                    sb.Append(seperator);
                }
                if (!typeof(T).IsValueType && array[i] == null) {
                    sb.Append("null");
                } else {
                    sb.Append(array[i].ToString());
                }
            }
            return sb.ToString();
        }

        /// <summary>
        /// Compares two arrays.
        /// </summary>
        /// <param name="array1">First array.</param>
        /// <param name="array2">Second array.</param>
        /// <param name="length">The number of bytes to compare starting at 0.</param>
        /// <returns>true, if equal.</returns>
        public static bool Compare<T>(T[] array1, T[] array2, int length) {
            if (array1.Length < length || array2.Length < length) {
                throw new ArgumentException("invalid length specified");
            }
            for (int i = 0; i < length; i++) {
                if (!array1[i].Equals(array2[i])) {
                    return false;
                }
            }
            return true;
        }
    }
}
